package org.example;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Client extends JFrame {

    // 数据库连接信息
    private final String url = "jdbc:mysql://localhost:3306/contact"; // 设置数据库URL，包括数据库名称
    private final String username = "root";
    private final String password = "314489";

    // 姓名、住址、电话输入框
    private JTextField nameField;
    private JTextField addressField;
    private JTextField phoneField;

    // JButton用于操作联系人
    private JButton addButton;
    private JButton deleteButton;
    private JButton viewButton;
    private JButton editButton;

    // JTable用于展示联系人信息
    private JTable contactTable;
    private DefaultTableModel tableModel;

    private Connection connection;



    // 构造函数
    public Client() {
//        连接数据库
        if (!connect()) {
            throw new RuntimeException("无法连接到数据库");
        }
//        初始化GUI界面
        initGUI();
    }

    public static void main(String[] args) {
//        连接数据库并初始化GUI界面
        new Client();
    }

    // 连接数据库
    private boolean connect() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url, username, password);
            System.out.println("成功连接到数据库");
            return true;
        } catch (ClassNotFoundException e) {
            System.err.println("JDBC 驱动程序类未找到：" + e.getMessage());
            return false;
        } catch (SQLException e) {
            System.err.println("SQL 连接错误：" + e.getMessage());
            return false;
        }
    }

//    初始化GUI
    private void initGUI() {
        // 设置窗口属性
        setTitle("个人通讯录管理系统");
        setSize(1000, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 定义字体
        Font font = new Font("微软雅黑", Font.PLAIN, 16); // 设置字体为微软雅黑，大小为16

        // 创建输入框和标签
        JPanel inputPanel = new JPanel(new FlowLayout());
        JLabel nameLabel = new JLabel("姓名:");
        nameLabel.setFont(font);
        inputPanel.add(nameLabel);

        nameField = new JTextField(15);
        nameField.setFont(font);
        inputPanel.add(nameField);

        JLabel addressLabel = new JLabel("住址:");
        addressLabel.setFont(font);
        inputPanel.add(addressLabel);

        addressField = new JTextField(15);
        addressField.setFont(font);
        inputPanel.add(addressField);

        JLabel phoneLabel = new JLabel("电话:");
        phoneLabel.setFont(font);
        inputPanel.add(phoneLabel);

        phoneField = new JTextField(15);
        phoneField.setFont(font);
        inputPanel.add(phoneField);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());

        addButton = new JButton("添加联系人");
        addButton.setFont(font);
        addButton.addActionListener(new AddContactListener());
        buttonPanel.add(addButton);

        deleteButton = new JButton("删除联系人");
        deleteButton.setFont(font);
        deleteButton.addActionListener(new DeleteContactListener());
        buttonPanel.add(deleteButton);

        viewButton = new JButton("查看联系人");
        viewButton.setFont(font);
        viewButton.addActionListener(new ViewContactListener());
        buttonPanel.add(viewButton);

        editButton = new JButton("修改联系人"); // 修改联系人按钮
        editButton.setFont(font);
        editButton.addActionListener(new EditContactListener()); // 添加监听器
        buttonPanel.add(editButton);

        // 数据表的初始化
        String[] columnNames = {"ID", "姓名", "电话", "住址"}; // 添加ID列
        tableModel = new DefaultTableModel(columnNames, 0);
        contactTable = new JTable(tableModel);
        contactTable.setFont(font);
        contactTable.setRowHeight(30); // 根据需要调整行高
        // 设置表头字体
        contactTable.getTableHeader().setFont(font); // 设置表头字体为加粗
        contactTable.getTableHeader().setPreferredSize(new Dimension(30, 40)); // 根据需要调整表头行高

        JScrollPane scrollPane = new JScrollPane(contactTable);

        // 添加组件到窗口
        add(inputPanel, BorderLayout.NORTH);
        add(buttonPanel, BorderLayout.CENTER);
        add(scrollPane, BorderLayout.SOUTH);

        setVisible(true);
    }


    // 添加联系人按钮的监听器
    private class AddContactListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
//            得到三个输入框的值
            String name = nameField.getText();
            String address = addressField.getText();
            String phone = phoneField.getText();

//            调用添加联系人的方法
            if (addContact(name, phone, address)) {
                JOptionPane.showMessageDialog(Client.this, "添加成功!");
                refreshContactList();
            } else {
                JOptionPane.showMessageDialog(Client.this, "添加失败!");
            }
        }
    }


    // 删除联系人按钮的监听器
    private class DeleteContactListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
//            获取选择的行
            int selectedRow = contactTable.getSelectedRow();
            if (selectedRow >= 0) {
                String id = (String) tableModel.getValueAt(selectedRow, 0); // 从表格中获取ID
//                调用删除联系人的方法
                if (deleteContact(id)) {
                    JOptionPane.showMessageDialog(Client.this, "删除成功!");
                    refreshContactList();
                } else {
                    JOptionPane.showMessageDialog(Client.this, "删除失败!");
                }
            } else {
                JOptionPane.showMessageDialog(Client.this, "请选择要删除的联系人!");
            }
        }
    }

    // 查看联系人按钮的监听器
    private class ViewContactListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
//            调用查询所有联系人的方法
            refreshContactList();
        }
    }

    // 修改联系人按钮的监听器
    private class EditContactListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            int selectedRow = contactTable.getSelectedRow();
            if (selectedRow >= 0) {
                String id = (String) tableModel.getValueAt(selectedRow, 0);
                String name = (String) tableModel.getValueAt(selectedRow, 1);
                String phone = (String) tableModel.getValueAt(selectedRow, 2);
                String address = (String) tableModel.getValueAt(selectedRow, 3);

                // 调用修改联系人的方法
                if (editContact(id, name, phone, address)) {
                    JOptionPane.showMessageDialog(Client.this, "修改成功!");
                    refreshContactList();
                } else {
                    JOptionPane.showMessageDialog(Client.this, "修改失败!");
                }
            } else {
                JOptionPane.showMessageDialog(Client.this, "请选择要修改的联系人!");
            }
        }
    }




    // 添加联系人的方法
    public boolean addContact(String name, String phone, String address) {
        // 检查输入框是否为空
        if (name == null || name.trim().isEmpty() ||
                phone == null || phone.trim().isEmpty() ||
                address == null || address.trim().isEmpty()) {
            return false; // 添加失败
        }

//        在数据库中执行SQL语句
        String query = "INSERT INTO contacts (name, phone, address) VALUES (?, ?, ?)";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, name);
            statement.setString(2, phone);
            statement.setString(3, address);
            statement.executeUpdate();
            return true; // 添加成功
        } catch (SQLException e) {
            e.printStackTrace();
            return false; // 添加失败
        }
    }

    // 删除联系人的方法
    public boolean deleteContact(String id) {
//        在数据库中执行SQL语句
        String query = "DELETE FROM contacts WHERE id = ?";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, id);
            statement.executeUpdate();
            return true; // 删除成功
        } catch (SQLException e) {
            e.printStackTrace();
            return false; // 删除失败
        }
    }

    // 刷新联系人列表
    public void refreshContactList() {
        tableModel.setRowCount(0); // 清空现有数据
        List<String[]> contacts = getContactList();
        for (String[] contact : contacts) {
            tableModel.addRow(contact);
        }
    }

    // 获取联系人的列表
    public List<String[]> getContactList() {
//        执行SQL语句
        List<String[]> contacts = new ArrayList<>();
        String query = "SELECT id, name, phone, address FROM contacts"; // 添加ID字段
        try (Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(query)) {
            while (resultSet.next()) {
                String id = String.valueOf(resultSet.getInt("id")); // 获取ID
                String name = resultSet.getString("name");
                String phone = resultSet.getString("phone");
                String address = resultSet.getString("address");
                contacts.add(new String[]{id, name, phone, address}); // 添加ID到联系人数组
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return contacts;
    }

    // 修改联系人的方法
    public boolean editContact(String id, String name, String phone, String address) {
        System.out.println(id);
        System.out.println(name);
        System.out.println(phone);
        System.out.println(address);
        // 检查输入框是否为空
        if (name == null || name.trim().isEmpty() ||
                phone == null || phone.trim().isEmpty() ||
                address == null || address.trim().isEmpty()) {
            System.out.println("有空");
            return false; // 修改失败
        }

        // 在数据库中执行SQL语句
        String query = "UPDATE contacts SET name = ?, phone = ?, address = ? WHERE id = ?";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, name);
            statement.setString(2, phone);
            statement.setString(3, address);
            statement.setString(4, id);
            statement.executeUpdate();
            return true; // 修改成功
        } catch (SQLException e) {
            e.printStackTrace();
            return false; // 修改失败
        }
    }



}
